// packageA/pages/addServes/addServes.js
let app = getApp();

var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
const {
  requestDataparams
} = require('../../../utils/request.js');
const {
  Handleimg
} = require('../../../utils/util.js')
Page({
  data: {
    minusStatus: 'disabled',
    addServesData: [],
    animatheightadd: {},
    showDialog: false,
    currentAddserve: null,
    portionNain: [],
    currentIndex: 0,
    currentItem: null,
    currentPrice: 0,
    totalPrice: 0,
    conferenceGoodTypeList: [],
    preTotlaPrice: '',
    prePageName: '',
    lists: [],
    conferenceRoomId: '',
    conferenceOrderId: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var preTotlaPrice = options.totlaPrice;
    var pageName = options.pageName;
    if (options.conferenceRoomId) {
      that.setData({
        conferenceRoomId: options.conferenceRoomId
      })
    }
    if (options.conferenceOrderId) {
      that.setData({
        conferenceOrderId: options.conferenceOrderId
      })
    }
    that.setData({
      prePageName: pageName
    })

    that.getAddServersData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease'
    })
    //先隐藏内容
    this.animation.translateY(331).step()
    this.setData({
      animatheightadd: this.animation.export()
    })
  },
  /* 点击减号 */
  bindMinus: function (e) {
    var that = this;
    var num = e.currentTarget.dataset.num;
    var itemId = e.currentTarget.dataset.index;
    var price = e.currentTarget.dataset.price;
    var addServesData = that.data.addServesData;
    if (num > 0) {
      num--;
    }
    var d1 = 0;
    for (var i = 0; i < addServesData.length; i++) {
      if (itemId == addServesData[i].id) {
        addServesData[i].num = num;
        addServesData[i].total_price = parseInt(num) * parseInt(price);
      } else {
        addServesData[i].total_price = parseInt(addServesData[i].num) * parseInt(addServesData[i].price);
      }
      d1 += parseInt(addServesData[i].total_price);
    }
    that.setData({
      addServesData: addServesData,
      currentPrice: d1
    })
  },
  /* 点击加号 */
  bindPlus: function (e) {
    var that = this;
    var num = e.currentTarget.dataset.num;
    var itemId = e.currentTarget.dataset.index;
    var addServesData = that.data.addServesData;
    var price = e.currentTarget.dataset.price;
    num++;
    var dd = 0;
    for (var i = 0; i < addServesData.length; i++) {
      if (itemId == addServesData[i].id) {
        addServesData[i].num = num;
        addServesData[i].total_price = parseInt(num) * parseInt(price);
      } else {
        addServesData[i].total_price = parseInt(addServesData[i].num) * parseInt(addServesData[i].price);
      }
      dd += parseInt(addServesData[i].total_price);
    }
    that.setData({
      addServesData: addServesData,
      currentPrice: dd
    })
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var num = e.detail.value;
    // 将数值与状态写回  
    this.setData({
      num: num
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getAddServersData: function () { //获取增值服务列表
    let that = this
    requestDataparams('/api/conferenceGoods', {}, 'GET').then(response => {
      var responseData = response.data.data;
      for (var i = 0; i < responseData.length; i++) {
        if (responseData[i].images) {
          responseData[i].images = applet_park_api_url_imgUrl + '/' + responseData[i].images.split(',')[0];
        }
        responseData[i]['num'] = 0;
        var conferenceGoodTypeList = responseData[i].conferenceGoodTypeList;
        if (conferenceGoodTypeList) {
          for (var j = 0; j < conferenceGoodTypeList.length; j++) {
            conferenceGoodTypeList[j]['chioceStatue'] = false;
          }
          conferenceGoodTypeList[0]['chioceStatue'] = true;
          responseData[i]['price'] = conferenceGoodTypeList[0].price;
          responseData[i]['goodTypeId'] = conferenceGoodTypeList[0].id;
          responseData[i]['goodTypeName'] = conferenceGoodTypeList[0].name;
          // responseData[i].price= conferenceGoodTypeList[0].price;
          // responseData[i].id= conferenceGoodTypeList[0].id;
        }
      }
      that.setData({
        addServesData: responseData
      })
    })

  },
  chioceGoodType(e) { //选择规格
    var that = this;
    var chioceId = e.currentTarget.dataset.goodid;
    var chiocePrice = e.currentTarget.dataset.goodprice;
    var lists = that.data.addServesData;
    var conferenceGoodTypeList = [];
    var dd = 0;
    for (var i = 0; i < lists.length; i++) {
      conferenceGoodTypeList = lists[i].conferenceGoodTypeList;
      for (var j = 0; j < conferenceGoodTypeList.length; j++) {
        if (chioceId == conferenceGoodTypeList[j].id) { //被选中的列
          lists[i]['goodTypeId'] = chioceId;
          lists[i]['goodTypeName'] = conferenceGoodTypeList[j].name;
          lists[i]['price'] = chiocePrice;
          that.change(i, chioceId, chiocePrice);
        }
      }
      lists[i].total_price = parseInt(lists[i].num) * parseInt(lists[i]['price']);
      dd += lists[i].total_price;
    }
    that.setData({
      addServesData: lists,
      currentPrice: dd
    })
  },
  change(index, chioceId, chiocePrice) {
    var that = this;
    var lists = that.data.addServesData;
    var chioceItem = lists[index].conferenceGoodTypeList;
    for (var i = 0; i < chioceItem.length; i++) {
      chioceItem[i].chioceStatue = false;
      if (chioceId == chioceItem[i].id) {
        chioceItem[i].chioceStatue = true;
      }
    }
  },
  backBefore() {
    var that = this;

    var lists = that.data.addServesData;
    var chioceList = [];
    var obj = '';
    if (that.data.prePageName == 'meetingOrderList') { //前一个页面是我的订单 需要在此页面直接付款
      for (var i = 0; i < lists.length; i++) {
        if (lists[i].num) {
          obj += lists[i].id + ':' + lists[i].goodTypeId + ':' + lists[i].num + ',';
        }
      }
      that.pay(obj);
    } else { //返回预约会议室再付款
      for (var i = 0; i < lists.length; i++) {
        if (lists[i].num != 0) {
          obj += lists[i].id + ':' + lists[i].goodTypeId + ':' + lists[i].num + ',';
          var obj1 = {
            goodId: lists[i].id,
            goodTypeId: lists[i].goodTypeId,
            number: lists[i].num,
            name: lists[i].name,
            content: lists[i].content,
            goodTypeName: lists[i].goodTypeName,
            images: lists[i].images,
            price: lists[i].price,
          }
          chioceList = chioceList.concat(obj1);
        }
      }


      wx.setStorageSync('chioceList', chioceList); //用户选择的增值服务
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2]; //上一个页面
      prevPage.setData({
        addServesPrice: that.data.currentPrice,
        conferenceOrderDetails: obj
      });
      prevPage.getAddServer();
      wx.navigateBack({
        delta: 1
      })
    }
  },
  pay(obj) { //支付
    let that = this;
    var totlaPrice = that.data.currentPrice + '00';
    // var beginTime = that.data.beginTime +':00';
    // var endTime = that.data.endTime +':00';
    var token = app.globalData.TOKEN || wx.getStorageSync('TOKEN');
    var openId = app.globalData.openId || wx.getStorageSync('OPENID');
    wx.request({
      url: applet_park_api_url + '/api/wechatPay/conferenceOrderDetail',
      method: 'POST',
      header: {
        Authorization: token,
        'Content-Type': "application/x-www-form-urlencoded",
      },
      data: {
        totalAmount: totlaPrice,
        conferenceRoomId: that.data.conferenceRoomId, //会议室ID
        goodIds: obj, //选中的产品
        conferenceOrderId: that.data.conferenceOrderId,
        openid: openId
      },
      success(res2) {
        if (res2.data.code == 0) {
          wx.requestPayment({
            timeStamp: res2.data.data.timeStamp,
            nonceStr: res2.data.data.nonceStr,
            package: res2.data.data.prepay_id,
            signType: 'MD5',
            paySign: res2.data.data.sign,
            paySource: 1,
            success(res) {

              wx.showToast({
                title: '支付成功',
              })
              setTimeout(function () { //刷新列表
                that.loadDatameetingorderlist();
              }, 500);
            },
            fail(res3) {

            }
          })

        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })

  },
  refuse: function () {
    //显示底部弹出层
    this.animation.translateY(0).step()
    this.setData({
      animatheightadd: this.animation.export()
    })
    this.setData({
      showDialog: true
    })
  },
  confirmDialog: function (e) {
    //隐藏底部
    this.setData({
      showDialog: false
    })
    this.animation.translateY(331).step()
    this.setData({
      animatheightadd: this.animation.export() //导出动画api , 页面执行动画
    });
  },
  showDialog(e) {
    let data = e.currentTarget.dataset.item
    this.setData({
      currentAddserve: data
    })
    this.getAddServesDetail(data.id)
    this.refuse()
  },
  // 获取规格详细信息
  getAddServesDetail(id) {
    let _this = this
    wx.request({
      url: applet_park_api_url + '/api/conferenceGoods/' + id,
      success(response) {
        if (response.data.code == 0) {
          _this.setData({
            portionNain: response.data.data
          })
        } else {
          wx.showToast({
            title: '服务器错误',
            icon: 'none'
          })
        }

      }
    })
  },
  // 点击份数触发
  protionTap(e) {
    this.setData({
      currentIndex: e.currentTarget.dataset.index,
      currentItem: e.currentTarget.dataset.item
    })
  },
  controlClick() {
    this.confirmDialog()
    let price = this.data.currentItem.price
    this.setData({
      currentPrice: price
    })
  },
})